package com.lonwin.mes2u8.controller;

import com.lonwin.mes2u8.domain.mes.MesBatchCodeInfo;
import com.lonwin.mes2u8.domain.mes.MesSaleOrderInfo;
import com.lonwin.mes2u8.domain.u8.*;
import com.lonwin.mes2u8.service.BatchCodeService;
import com.lonwin.mes2u8.service.CustomerAppService;
import com.lonwin.mes2u8.service.InventoryAppService;
import com.lonwin.mes2u8.service.SaleOrderAppService;
import com.lonwin.mes2u8.util.MyQueueUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.Queue;
import java.util.stream.Collectors;

/**
 * 销售订单操作
 *
 * @author DELL
 * @Date 2023-12-15 17:31
 */
@Controller
@RequestMapping("/fxtSaleOrder")
@Slf4j
public class SaleOrderController {
    @Resource
    private BatchCodeService batchCodeService;

    @Resource
    private CustomerAppService customerAppService;

    @Resource
    private SaleOrderAppService saleOrderAppService;
    @Resource
    private InventoryAppService inventoryAppService;

    @GetMapping("/add")
    // public String addSaleOrder(@RequestParam String start, @RequestParam String end) {
    public String addSaleOrder() {
        log.info("SaleOrderController.addSaleOrder start");
        // 获取mes销售订单列表
        List<MesBatchCodeInfo> mesBatchCodeInfoList = batchCodeService.queryMesBatchList();

        if (mesBatchCodeInfoList.isEmpty()) {
            log.info("SaleOrderController addSaleOrder result 1 : query 0 , add 0");
            return "";
        }

        List<String> batchCodeList = mesBatchCodeInfoList.stream().map(MesBatchCodeInfo::getBno)
                .filter(s -> !s.startsWith("22") && !s.startsWith("23"))
                .collect(Collectors.toList());

        return addSaleOrder(batchCodeList);
    }

    public String addSaleOrder(List<String> batchCodeList) {

        // 遍历筛选要录入的订单
        List<String> mesNewSaleOrderResultList = batchCodeList.stream()
                .filter(batchCode -> saleOrderAppService.isNotExistOnU8(U8SaleOrderQueryParam.builder().id(batchCode).build()))
                .collect(Collectors.toList());

        if (mesNewSaleOrderResultList.isEmpty()) {
            log.info("SaleOrderController addSaleOrder result 2 : query {} , add 0", batchCodeList.size());
            return "";
        }

        Queue<DefineSyncResponse> failedObj = new LinkedList<>();
        StringBuilder addU8FailedInventories = new StringBuilder();
        StringBuilder addU8Failedcustomers = new StringBuilder();

        for (String batchCode : mesNewSaleOrderResultList) {
            Queue<DefineSyncResponse> inventoryAndCustomerQueue = new LinkedList<>();
            // 获取mes销售订单中的存货列表
            List<MesSaleOrderInfo> mesSaleOrderResult = saleOrderAppService.getMesSaleOrderInfo(batchCode);

            // 获取存货列表失败
            if (mesSaleOrderResult.isEmpty()) {
                log.error("SaleOrderController addSaleOrder get mes order info failed : {}", batchCode);
                continue;
            }

            // 将订单中系统不存在的存货录入系统
            for (MesSaleOrderInfo mesSaleOrderInfo : mesSaleOrderResult) {
                U8CommonSyncResponse inventoryFlag = inventoryAppService.addInventoryOfU8IfNotExist(mesSaleOrderInfo.getProductIdentification());
                if (Objects.nonNull(inventoryFlag)) {
                    // 记录哪些存货未录入成功
                    inventoryAndCustomerQueue.add(DefineSyncResponse.buildSelfBySyncResponse(inventoryFlag, mesSaleOrderInfo.getBno(), MyObjTypeEnum.INVENTORY));
                }
            }

            // 判断客户是否存在
            for (MesSaleOrderInfo mesSaleOrderInfo : mesSaleOrderResult) {
                U8CommonSyncResponse customerFlag = customerAppService.addCustomerToU8IfNotExist(mesSaleOrderInfo.buildU8CustomerAddParam());
                // 记录哪些客户未录入成功
                if(Objects.nonNull(customerFlag)) {
                    inventoryAndCustomerQueue.add(DefineSyncResponse.buildSelfBySyncResponse(customerFlag, mesSaleOrderInfo.getCno(), MyObjTypeEnum.CUSTUMER));
                }
            }

            // 判断客户和存货是否录入成功
            Queue<DefineSyncResponse> inventoryAndCustomerResult = MyQueueUtil.checkQueueSuccess(inventoryAndCustomerQueue);
            if (!inventoryAndCustomerResult.isEmpty()) {
                // 说明有客户或存货未录入完成
                DefineSyncResponse respTmp = null;
                while (Objects.nonNull(respTmp = inventoryAndCustomerResult.poll())) {
                    if (MyObjTypeEnum.CUSTUMER.equals(respTmp.getType())) {
                        // 客户未录入成功
                        log.error("SaleOrderController.addSaleOrder add customer failed : {} - {}", respTmp.getCode(), respTmp.getMessage());
                        addU8Failedcustomers.append(respTmp.getCode()).append(",");
                    }
                    if (MyObjTypeEnum.INVENTORY.equals(respTmp.getType())) {
                        // 存货未录入成功
                        log.error("SaleOrderController.addSaleOrder add inventory failed : {} - {}", respTmp.getCode(), respTmp.getMessage());
                        addU8FailedInventories.append(respTmp.getCode()).append(",");
                    }
                    failedObj.add(respTmp);
                }
                continue;
            }

            // 录入销售订单
            U8SaleOrderAddParam u8SaleOrderAddParam = U8SaleOrderAddParam.buildU8SaleOrderAddParamBySaleOrderInfoList(mesSaleOrderResult);
            if (Objects.isNull(u8SaleOrderAddParam)) {
                log.error("SaleOrderController.addSaleOrder u8SaleOrderAddParam build failed : {} add param is null", batchCode);
                continue;
            }
            U8CommonSyncResponse addSaleOrderToU8Flag = saleOrderAppService.addSaleOrderToU8(u8SaleOrderAddParam);
            if (Objects.isNull(addSaleOrderToU8Flag)) {
                log.error("SaleOrderController.addSaleOrder add sale order failed : {}", u8SaleOrderAddParam.getCode());
                continue;
            }
            DefineSyncResponse responseSuccess = MyQueueUtil.isResponseSuccess(DefineSyncResponse.buildSelfBySyncResponse(addSaleOrderToU8Flag, u8SaleOrderAddParam.getCode(), MyObjTypeEnum.SALEORDER));
            if (Objects.nonNull(responseSuccess)) {
                // 销售订单未录入成功
                log.error("SaleOrderController.addSaleOrder 5 add sale order failed : {} - {}", batchCode, responseSuccess.getMessage());
                failedObj.add(responseSuccess);
            }

        }
        log.info("SaleOrderController.addSaleOrder add customer failed {} : {}", addU8Failedcustomers.toString().split(",").length-1, addU8Failedcustomers);
        log.info("SaleOrderController.addSaleOrder add inventory failed {} : {}", addU8FailedInventories.toString().split(",").length-1, addU8FailedInventories);
        log.info("SaleOrderController.addSaleOrder result 3 query {} success {} failed {}", batchCodeList.size(), batchCodeList.size()-failedObj.size(), failedObj.size());
        log.info("SaleOrderController.addSaleOrder end");
        return "";
    }
}
